import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt

img1 = cv.imread('/Users/wanggh/Desktop/aa2.png', cv.IMREAD_GRAYSCALE)  # queryImage
# img2 = cv.imread('/Users/wanggh/Desktop/a.jpeg', cv.IMREAD_GRAYSCALE)  # trainImage
img2 = cv.imread('/Users/wanggh/Desktop/original.jpeg', cv.IMREAD_GRAYSCALE)  # trainImage
# 初始化SIFT描述符
sift = cv.ORB_create()
# 基于SIFT找到关键点和描述符
# img1 = cv.cvtColor(img1, cv.COLOR_BGR2GRAY)
# img2 = cv.cvtColor(img2, cv.COLOR_BGR2GRAY)
kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)
# 默认参数初始化BF匹配器
# bf = cv.BFMatcher()
# matches = bf.knnMatch(des1, des2, k=2)
bf = cv.BFMatcher(cv.NORM_HAMMING2, crossCheck=True)  # 匹配描述符.
matches = bf.match(des1, des2)

# 应用比例测试
matches = sorted(matches, key=lambda x: x.distance)
# cv.drawMatchesKnn将列表作为匹配项。
img3 = cv.drawMatches(img1, kp1, img2, kp2, matches[:10], None, flags=cv.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)
cv.imshow("test", img3)
cv.waitKey(0)
cv.destroyAllWindows()
